package com.yjs.jiaohao.listener;

import com.sun.jna.Callback;
import com.sun.jna.Native;
import com.sun.jna.win32.StdCallLibrary;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Component
public class Call implements ApplicationListener<ContextRefreshedEvent> {

    @Value("${jiaohao.cuankou}")
    public  Integer cuankou;

    @Autowired
    private JdbcTemplate jdbcTemplate;


    public static JdbcTemplate staticJdbcTemplate;



    public interface JnaTestCall extends StdCallLibrary {
        JnaTestCall INSTANCE = (JnaTestCall)Native.loadLibrary("CallDll",JnaTestCall.class);
        interface JavaCallback extends Callback
        {
            int OnCheck(int a,String c);
        }

        interface JavaCallbackoncall extends Callback
        {
            int OnCall(int a,int b,String c);
        }

        interface JavaCallbackOnScore extends Callback
        {
            int OnScore(int addr, int star, int flag);
        }

        int OpenCaller(int com,int falgs);
        int checkCaller(int addr);
        int BeepAll(int times,String addr);
        int Show2Caller(int addr,String str);
        long AddWait(String addrs);
        void CloseCaller();
        int LoadOnCall(JavaCallbackoncall OnCall);
        int LoadOnCheck(JavaCallback OnCheck);
        int LoadOnScore(JavaCallbackOnScore OnCall);

        public static  JavaCallback callback=new JavaCallback()
        {
            @Override
            public int OnCheck(int a,String c)
            {
                return 0;
            }
        };

        public static  JavaCallbackoncall callbackoncall=new JavaCallbackoncall()
        {
            @Override
            public int OnCall(int a, int b,String c)
            {
                String queryWindow = " select * from sys_window where  call_code = '"+ a +"'";
                List<Map<String,Object>> winList = staticJdbcTemplate.queryForList(queryWindow);
                if(winList.size() == 1 && winList.get(0).get("win_code") != null){
                    String winCode = winList.get(0).get("win_code").toString();
                    if(b==15){
                        if(!StringUtils.isEmpty(c)){
                            if(Integer.parseInt(c)<10){
                                if(!winList.get(0).get("use_flag").toString().equals("2")){
                                    //执行按钮命令
                                    if(Integer.parseInt(c) == 0){
                                        //暂停
                                        String updateSql = " update sys_window set use_flag = 1 where call_code = '"+ a +"'";
                                        staticJdbcTemplate.execute(updateSql);
                                    }else if(Integer.parseInt(c) == 4){
                                        //退出
                                        String updateSql = " update sys_window set use_flag = 2,login_user = null where call_code = '"+ a +"'";
                                        staticJdbcTemplate.execute(updateSql);
                                    }
                                }

                            }else{
                                //工号登录
                                String sql = " select * from sys_user where login_name = '"+c+"'";
                                List<Map<String,Object>> list = staticJdbcTemplate.queryForList(sql);
                                if(list.size()==1){
                                    String loginName = list.get(0).get("login_name").toString();
                                    String updateSql = " update sys_window set use_flag = 0,login_user = '"+loginName+"' where call_code = '"+ a +"'";
                                    staticJdbcTemplate.execute(updateSql);
                                    //查询当前等待人数
                                    show(a,winCode,1);
                                }
                            }
                        }
                    }else if(b==13 || b==12){
                        //重呼或者呼叫
                        if(!winList.get(0).get("use_flag").toString().equals("2")){
                            if(winList.get(0).get("use_flag").toString().equals("1")){
                                String updateSql = " update sys_window set use_flag = 0 where call_code = '"+ a +"'";
                                staticJdbcTemplate.execute(updateSql);
                            }
                            if(b==13){
                                //增加呼叫次数
                                String countUpdate = " update qh_quhao set call_count = call_count + 1 where do_win_code = '" + winCode + "' and status = 0 " ;
                                staticJdbcTemplate.execute(countUpdate);
                            }else{

                                //获取当前登录人信息
                                String userSql = " select * from sys_user where login_name = '"+ winList.get(0).get("login_user").toString() +"'";
                                List<Map<String,Object>> userList = staticJdbcTemplate.queryForList(userSql);
                                if(userList.size()==1){
                                    //更新当前呼叫信息
                                    String statusUpdate = " update qh_quhao set `status` = 2 ,`end_time`= sysDate() where do_win_code = '" + winCode + "' and status = 0 " ;
                                    staticJdbcTemplate.execute(statusUpdate);
                                    String userName = userList.get(0).get("user_name").toString();
                                    //呼叫
                                    String sql = "update qh_quhao set `status` = 0,`do_by`= '"+userName+"',`do_win_code`= '"+winCode+"',`do_time` = sysDate()  where FIND_IN_SET('"+ winCode +"', wait_win_codes) and `status` = 1 ORDER BY status,type desc,create_time asc limit 1";
                                    staticJdbcTemplate.execute(sql);
                                    //刷新相同业务窗口等待人数
                                    String quhaoSql = "select * from qh_quhao where `status` = 0 and `do_win_code`= '"+winCode+"'";
                                    List<Map<String,Object>> qhList =  staticJdbcTemplate.queryForList(quhaoSql);
                                    if(qhList.size()==1){
                                        String[] waitWinCodes = qhList.get(0).get("wait_win_codes").toString().split(",");
                                        for (int i=0;i<waitWinCodes.length;i++){
                                            if(!waitWinCodes[i].equals(winCode)){
                                                String winSql = " select * from sys_window where win_code = '"+waitWinCodes[i]+"'";
                                                List<Map<String,Object>> list = staticJdbcTemplate.queryForList(winSql);
                                                if(list.size()==1){
                                                    if(!list.get(0).get("use_flag").toString().equals("2")){
                                                        int callCode = Integer.parseInt(list.get(0).get("call_code").toString());
                                                        show(callCode,waitWinCodes[i],2);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            show(a,winCode,2);
                        }

                    }else if(b==10 || b==11){
                        //验证是否登录
                        if(!winList.get(0).get("use_flag").toString().equals("2")){
                            show(a,winCode,2);
                        }
                    }
                }
                return 0;
            }
        };

        public static  JavaCallbackOnScore callbackOnScore=new JavaCallbackOnScore()
        {
            @Override
            public int OnScore(int addr, int star, int flag)
            {
                String queryWindow = " select * from sys_window where  call_code = '"+ addr +"'";
                List<Map<String,Object>> winList = staticJdbcTemplate.queryForList(queryWindow);
                if(winList.size() == 1 && winList.get(0).get("win_code") != null){
                    String winCode = winList.get(0).get("win_code").toString();
                    if(!winList.get(0).get("use_flag").toString().equals("2")){
                        if(star == 255){
                            star = 2;
                        }
                        //更新评价状态
                        String sql = " update qh_quhao set pj_status = 1 ,score = "+star+" where do_win_code =  '"+winCode+"' and status = 0 ";
                        staticJdbcTemplate.execute(sql);

                    }

                }
                return 0;
            }

        };
    }

    public static void show(int a, String winCode,int flag){
        //查询当前等待人数
        String countSql = " select * from qh_quhao where FIND_IN_SET('"+winCode+"', wait_win_codes) and `status` = 1 ";
        List<Map<String,Object>> qhList = staticJdbcTemplate.queryForList(countSql);
        String waitNum = "00";
        if(qhList.size()<10){
            waitNum = "0"+qhList.size();
        }else if(qhList.size()<100){
            waitNum = ""+qhList.size();
        }else if(qhList.size()>=100){
            waitNum = ""+qhList.size();
            waitNum = waitNum.substring(waitNum.length()-2);
        }
        if(flag==1){
            JnaTestCall.INSTANCE.Show2Caller(a,waitNum+"0000");
        }else{
            //当前呼叫号码
            String qhSql = " select * from qh_quhao where FIND_IN_SET('"+winCode+"', wait_win_codes) and `status` = 0 ";
            List<Map<String,Object>> list = staticJdbcTemplate.queryForList(qhSql);
            if(list.size()==1){
                String num = list.get(0).get("order_code").toString();
                num = num.substring(num.length()-3);
                String type = list.get(0).get("type").toString();
                JnaTestCall.INSTANCE.Show2Caller(a,waitNum+type+num);
            }else{
                JnaTestCall.INSTANCE.Show2Caller(a,waitNum+"0000");
            }

        }

    }

    public static void add(int a, String winCode){
        //查询当前等待人数
        String countSql = " select * from qh_quhao where FIND_IN_SET('"+winCode+"', wait_win_codes) and `status` = 1 ";
        List<Map<String,Object>> qhList = staticJdbcTemplate.queryForList(countSql);
        String waitNum = "00";
        if(qhList.size()<10){
            waitNum = "0"+qhList.size();
        }else if(qhList.size()<100){
            waitNum = ""+qhList.size();
        }else if(qhList.size()>=100){
            waitNum = ""+qhList.size();
            waitNum = waitNum.substring(waitNum.length()-2);
        }

        //当前呼叫号码
        String qhSql = " select * from qh_quhao where FIND_IN_SET('"+winCode+"', wait_win_codes) and `status` = 0 ";
        List<Map<String,Object>> list = staticJdbcTemplate.queryForList(qhSql);
        if(list.size()==1){
            String num = list.get(0).get("order_code").toString();
            num = num.substring(num.length()-3);
            String type = list.get(0).get("type").toString();
            JnaTestCall.INSTANCE.Show2Caller(a,waitNum+type+num);
        }else{
            JnaTestCall.INSTANCE.Show2Caller(a,waitNum+"0000");
        }
    }


    @RabbitListener(queues = {"${jiaohao.area}"})
    public void receive(String message){
        String[] winCode = message.split(",");
        for(int i = 0;i<winCode.length;i++){
            String sql = " select * from sys_window where win_code = '"+winCode[i]+"'";
            List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
            if(list.size()==1){
                if(!list.get(0).get("use_flag").toString().equals("2")){
                    add(Integer.parseInt(list.get(0).get("call_code").toString()),list.get(0).get("win_code").toString());
                }
            }

        }
    }


    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        staticJdbcTemplate = this.jdbcTemplate;
        try {
            test();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void test() {
        JnaTestCall.INSTANCE.OpenCaller(cuankou,1);
        JnaTestCall.INSTANCE.LoadOnCall(JnaTestCall.callbackoncall );
        JnaTestCall.INSTANCE.LoadOnCheck(JnaTestCall.callback );
        JnaTestCall.INSTANCE.LoadOnScore(JnaTestCall.callbackOnScore );

        try {
            System.in.read();
        } catch (IOException e) {

        }
        JnaTestCall.INSTANCE.CloseCaller();
        System.exit(0);
    }


}
